<template>
    <div class="dashboard-container" id="model-app">
        <div class="container">
            <!-- 模型页面的Nav -->
            <div class="tableBar">
                <el-input v-model="input" placeholder="请输入模型名称" style="width: 250px" clearable
                    @keyup.enter.native="handleQuery">
                    <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer" @click="init"></i>
                </el-input>
                <div class="tableLab" v-if="userInfo.position == 'manager' || userInfo.position == 'admin'">
                    <span class="span-btn delBut non" @click="deleteHandle('批量', null)">批量删除</span>
                    <span class="span-btn blueBug non" @click="statusHandle('1')">批量展示</span>
                    <span style="border:none;" class="span-btn delBut non" @click="statusHandle('0')">批量隐藏</span>
                    <el-button type="primary" @click="addFoodtype('add')">+ 新建模型</el-button>
                </div>
            </div>
            <!-- 模型的具体展示 -->
            <el-table :data="tableData" stripe class="tableBox" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="25"></el-table-column>
                <el-table-column prop="name" label="模型名称"></el-table-column>
                <el-table-column prop="image" label="图片" align="center">
                    <template slot-scope="{ row }">
                        <el-image style="width: auto; height: 40px; border:none; cursor: pointer;"
                            :src="getImage(row.image)" :preview-src-list="row.imageUrlList">
                            <div slot="error" class="image-slot">
                                <img src="../../assets/images/noImg.png" style="width: auto; height: 40px; border:none;">
                            </div>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="categoryName" label="模型分类"></el-table-column>
                <el-table-column prop="exhibitionName" label="隶属展厅"
                    v-if="userInfo.position == 'exhibitor'"></el-table-column>
                <!-- TODO 这里预览相应逻辑没做 -->
                <el-table-column label="预览">
                    <template slot-scope="{ row }">
                        <el-button icon="el-icon-search" circle size="small"
                            @click="Preview(row.androidModelPath)"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="展示状态">
                    <template slot-scope="scope">
                        <span style="margin-right: 10px;">{{ scope.row.status == '0' ? '隐藏' : '展示' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="最后操作时间"></el-table-column>
                <el-table-column label="操作" v-if="userInfo.position == 'manager' || userInfo.position == 'admin'"
                    width="160" align="center">
                    <!-- 下面是修改等状态按钮 -->
                    <template slot-scope="scope">
                        <el-button type="text" size="small" class="blueBug"
                            @click="addFoodtype(scope.row.id)">修改</el-button>
                        <el-button type="text" size="small" class="blueBug" @click="statusHandle(scope.row)">{{
                            scope.row.status == '0' ? '展示' : '隐藏' }}</el-button>
                        <el-button type="text" size="small" class="delBut non"
                            @click="deleteHandle('单删', scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" v-if="userInfo.position == 'exhibitor'" width="160" align="center">
                    <!-- 下面是修改等状态按钮 -->
                    <template slot-scope="scope">
                        <el-button type="text" size="small" class="blueBug"
                            @click="addBannerModel(scope.row)">设置为推荐模型</el-button>
                        <el-button type="text" size="small" class="delBut non" @click="removeBannerModel(scope.row)">
                            取消设置为推荐模型
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 下面是分页Page的相关配置 -->
            <el-pagination class="pageList" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="counts" @size-change="handleSizeChange"
                :current-page.sync="page" @current-change="handleCurrentChange"></el-pagination>
        </div>
        <el-dialog title="预览" :visible.sync="dialogVisible" width="60%">
            <!-- :textureImage="this.texturesList"  -->
            <div style="height: 800px;display: flex;
 justify-content: center; align-items: center">
                <el-progress :percentage="this.downloadProgress" type="circle" :width="400" color="#ffc200"
                    v-if="this.downloadProgress > 0 && this.downloadProgress < 100"></el-progress>
                <vue3dLoader v-else :width="700" :height="800" :fileType="'gltf'" :cameraPosition="{ x: 0, y: 0, z: 0.35 }"
                    :filePath="this.glbFileUrl" :backgroundColor="0x000000"></vue3dLoader>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getModelPage, deleteModel, modelStatusByStatus, addBannerModel, removeBannerModel, downloadGLBPreview } from '../../api/model'; // 导入需要的API函数
import { vue3dLoader } from "vue-3d-loader";
import { download, upload, uploadModel } from '../../api/common'

export default {
    data() {
        return {
            dialogVisible: false,
            input: '',
            counts: 0,
            page: 1,
            pageSize: 10,
            tableData: [],
            modelState: '',
            checkList: [],
            imageUrlList: [],
            glbFileUrl: '',
            downloadProgress: 0,
            // texturesList:[],
        };
    },
    components: {
        vue3dLoader
    },
    computed: {},
    created() {
        this.init();
        const userInfo = window.localStorage.getItem("userInfo");
        if (userInfo) {
            this.userInfo = JSON.parse(userInfo);
        }
        if (this.userInfo.position === "exhibitor") {
            console.log("展厅管理员驾到，统统闪开")
        }
    },
    methods: {
        async init() {
            const params = {
                page: this.page,
                pageSize: this.pageSize,
                name: this.input ? this.input : undefined,
            };
            await getModelPage(params)
                .then((res) => {
                    if (String(res.code) === '1') {
                        //防止不存在模型时进行查询导致报错
                        if (res.data != null) {
                            this.tableData = res.data.records || [];
                            this.counts = res.data.total;

                            // 遍历this.tableData数组
                            this.tableData.forEach(item => {
                                // 将image属性按逗号分割成数组，并存入imageUrlList属性
                                item.imageUrlList = item.image.split(',');

                                // 将image属性修改为按逗号分割后的第一个数据
                                item.image = item.imageUrlList[0];

                                //     downloadGLB({ name: item.androidModelPath }).then(url => {
                                //     this.glbFileUrl = url;

                                // });
                            });

                        }
                    }
                })
                .catch((err) => {
                    this.$message.error('请求出错了：' + err);
                });
        },

        Preview(androidModelPath) {
            console.log("androidModelPath:" + androidModelPath)

            // 初始化进度为0
            this.downloadProgress = 0;
            this.glbFileUrl = ''

            // 发起文件下载请求
            downloadGLBPreview({ name: androidModelPath }, (progressEvent) => {
                // 计算下载进度
                console.log('Download Progress:', progressEvent.loaded, '/', progressEvent.total);
                this.downloadProgress = Math.round(progressEvent.loaded / progressEvent.total * 100);
            }).then((url) => {
                // 下载完成后，设置文件URL并显示对话框
                this.glbFileUrl = url;

            });
            this.dialogVisible = true
        },

        getImage(image) {
            return image;
        },
        handleQuery() {
            this.page = 1;
            this.init();
        },
        // 添加
        addFoodtype(st) {
            // 根据修改或者添加模型来决定跳转的add.html的模样
            if (st === 'add') {
                window.parent.menuHandle(
                    {
                        id: '/add-model',
                        name: '添加模型',
                        index: "3",
                    },
                    true
                );
                this.$router.push('/add-model'); // Navigate to the "Add Member" page
            } else {
                window.parent.menuHandle(
                    {
                        id: '/edit-model/' + st,
                        name: '修改模型',
                        index: "3",
                    },
                    true
                );

                this.$router.push(`/edit-model/${st}`); // Navigate to the "Edit Member" page with ID
            }
        },
        // TODO:

        addBannerModel(row) {
            console.log(row)
            let params = row;

            addBannerModel(params).then(res => {
                if (res.code === 1) {
                    this.$message.success('设置成功')
                } else {
                    this.$message.error(res.data.msg || '操作失败')
                }
            }).catch(err => {
                this.$message.error('请求出错了：' + err)
            })

        },
        removeBannerModel(row) {
            console.log(row)
            let params = row;

            removeBannerModel(params).then(res => {
                if (res.code === 1) {
                    this.$message.success('取消设置成功')
                } else {
                    this.$message.error(res.data.msg || '操作失败')
                }
            }).catch(err => {
                this.$message.error('请求出错了：' + err)
            })

        },
        // 删除
        deleteHandle(type, id) {
            if (type === '批量' && id === null) {
                if (this.checkList.length === 0) {
                    return this.$message.error('请选择删除对象');
                }
            }
            this.$confirm('确认删除该模型, 是否继续?', '确定删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                deleteModel(type === '批量' ? this.checkList.join(',') : id)
                    .then((res) => {
                        if (res.code === 1) {
                            this.$message.success('删除成功！');
                            this.handleQuery();
                        } else {
                            this.$message.error(res.data.msg || '操作失败');
                        }
                    })
                    .catch((err) => {
                        this.$message.error('请求出错了：' + err);
                    });
            }).catch(() => {
                // 用户点击取消按钮的处理逻辑
                // 可以不做任何处理，或者在这里添加一些取消操作的逻辑
            });
        },
        // 状态更改
        statusHandle(row) {
            let params = {};
            if (typeof row === 'string') {
                if (this.checkList.length === 0) {
                    this.$message.error('批量操作，请先勾选操作模型！');
                    return false;
                }
                params.id = this.checkList.join(',');
                params.status = row;
            } else {
                params.id = row.id;
                params.status = row.status ? '0' : '1';
            }
            this.modelState = params;
            this.$confirm('确认更改该模型状态?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                // 上架隐藏---上架隐藏接口
                modelStatusByStatus(this.modelState)
                    .then((res) => {
                        if (res.code === 1) {
                            this.$message.success('模型状态已经更改成功！');
                            this.handleQuery();
                        } else {
                            this.$message.error(res.data.msg || '操作失败');
                        }
                    })
                    .catch((err) => {
                        this.$message.error('请求出错了：' + err);
                    });
            });
        },
        // 全部操作
        handleSelectionChange(val) {
            let checkArr = [];
            val.forEach((n) => {
                checkArr.push(n.id);
            });
            this.checkList = checkArr;
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.init();
        },
        handleCurrentChange(val) {
            this.page = val;
            this.init();
        },
    },
};
</script>
  
<style scoped>
/* 样式可以在这里定义 */
</style>
  